/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import POJO.NguoiDungPOJO;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.sql.ResultSet;
import ultil.MySqlDataAccessHelper;

/**
 *
 * @author NGUYEN CONG BINH
 */
public class NguoiDungDAO {

    public static NguoiDungPOJO DangNhap(String _tenDangNhap, String _matKhau) {
        NguoiDungPOJO nguoidung = null;
        try {

            String matKhau = encryptPass(_matKhau);
            String sql = "SELECT * FROM nguoidung where TenDangNhap = '" + _tenDangNhap + "' and MatKhau = '" + matKhau + "' and macapbac = 3";
            MySqlDataAccessHelper helper = new MySqlDataAccessHelper();
            helper.open();
            ResultSet rs = helper.executeQuery(sql);
            if (rs.next()) {
                nguoidung = new NguoiDungPOJO();
                nguoidung.setMaNguoiDung(rs.getInt("maNguoiDung")); 
                nguoidung.setTenDangNhap(rs.getString("tenDangNhap"));
                nguoidung.setMatKhau(rs.getString("matKhau"));
                nguoidung.seteMail(rs.getString("eMail"));
                nguoidung.setDiaChi(rs.getString("diaChi"));
                nguoidung.setDienThoai(rs.getInt("dienThoai"));
                nguoidung.setHoTenNguoiDung(rs.getString("hoTenNguoiDung"));
            }
            helper.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return nguoidung;
    }

    public static boolean dangky(NguoiDungPOJO kh) {
        boolean kq = false;
        try {
            String sql = String.format("INSERT INTO nguoidung( tenDangNhap, matKhau, maCapBac, hoTenNguoiDung,diaChi, eMail, dienThoai) VALUES ('%s','%s', %d ,'%s','%s','%s',%d)", kh.getTenDangNhap(), kh.getMatKhau(),kh.getMaCapBac() ,kh.getHoTenNguoiDung(), kh.getDiaChi(), kh.geteMail(), kh.getDienThoai());
            MySqlDataAccessHelper helper = new MySqlDataAccessHelper();
            helper.open();
            int n = helper.executeUpdate(sql);
            if (n == 1) {
                kq = true;
            }
            helper.close();
        } catch (Exception ex) {
            System.err.println(ex);
        }
        return kq;
    }

    public static String encryptPass(String pass) {
        String passEncrypt;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e);
        }
        md5.update(pass.getBytes());
        BigInteger dis = new BigInteger(1, md5.digest());
        passEncrypt = dis.toString();
        return passEncrypt;
    }
}
